<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Sales\Service;

use Admin\Data\Config;
use Doctrine\ORM\EntityManager;
use Sales\Entity\Order;
use Sales\Entity\OrderGoods;

class OrderGoodsManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加订单商品
     * @param $cartGoodsList
     * @param $defaultCurrency
     * @param Order $order
     * @return array
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addOrderGoods($cartGoodsList, $defaultCurrency, Order $order)
    {
        $cartIdArray = [];
        foreach ($cartGoodsList as $goodsValue) {
            $orderGoods = new OrderGoods();
            $orderGoods->setOrderId($order->getOrderId());
            $orderGoods->setGoodsId($goodsValue[0]->getGoodsId());
            $orderGoods->setGoodsName($goodsValue['goodsName']);
            $orderGoods->setGoodsItem($goodsValue['goodsItem']);
            $orderGoods->setGoodsPrice($goodsValue['goodsPrice'] * $defaultCurrency['rate']);

            //对商品封面进行保存，如果是本地图片，则将商品封面复制到订单对应的目录
            $goodsThumbnailImage = $this->copyOrderGoodsImage($goodsValue['goodsThumbnailImage'], $goodsValue[0]->getGoodsId());
            if(!empty($goodsThumbnailImage)) $orderGoods->setGoodsImage($goodsThumbnailImage);

            if(isset($goodsValue['specGoodsTagInfo'])) {
                $tagStr = '';
                foreach ($goodsValue['specGoodsTagInfo'] as $specInfo) {
                    $tagStr .= $specInfo['tagGroupName'] . '：' . $specInfo[0]->getTagName() . ' ';
                }
                $orderGoods->setInSpecGoodsStr(rtrim($tagStr, ' '));
                $orderGoods->setInSpecGoodsId($goodsValue[0]->getInSpecGoodsId());
                $goodsWeightAmount = $goodsValue['specGoodsWeight'] * $goodsValue['goodsWeightConversion'] * $goodsValue[0]->getBuyNum();
            } else $goodsWeightAmount = $goodsValue['goodsWeight'] * $goodsValue['goodsWeightConversion'] * $goodsValue[0]->getBuyNum();

            $orderGoods->setGoodsType($goodsValue['goodsType']);
            $orderGoods->setBuyNum($goodsValue[0]->getBuyNum());
            $orderGoods->setBaseGoodsAmount($goodsValue['goodsAmount']);
            $orderGoods->setGoodsAmount($goodsValue['goodsAmount'] * $defaultCurrency['rate']);
            $orderGoods->setGoodsWeightAmount($goodsWeightAmount);
            $orderGoods->setUserId($order->getUserId());
            $orderGoods->setOrder($order);

            $this->entityManager->persist($orderGoods);
            $this->entityManager->flush();
            //$this->entityManager->clear(OrderGoods::class);

            $cartIdArray[] = $goodsValue[0]->getCartId();
        }

        return $cartIdArray;
    }

    /**
     * 编辑订单商品
     * @param $data
     * @param OrderGoods $orderGoods
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editOrderGoods($data, OrderGoods $orderGoods)
    {
        $orderGoods->valuesSet($data);
        $this->entityManager->flush();
    }

    /**
     * 更改订单商品的发货状态
     * @param $status
     * @param $orderId
     * @param int $goodsId
     * @return bool
     */
    public function changeOrderGoodsStatus($status, $orderId, $goodsId = 0)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(OrderGoods::class, 'g')
            ->set('g.goodsStatus', ':goodsStatus')->setParameter('goodsStatus', $status)
            ->where('g.orderId = :orderId')->setParameter('orderId', $orderId)
            ->andWhere('g.goodsType = 1');
        if($goodsId > 0) $qb->andWhere('g.goodsId = :goodsId')->setParameter('goodsId', $goodsId);

        $qb->getQuery()->execute();

        return true;
    }

    /**
     * 订单商品单独配送发货设置
     * @param $data
     * @param $status
     * @param $orderId
     * @param $deliveryName
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function changeOrderGoodsShip($data, $status, $orderId, $deliveryName)
    {
        foreach ($data['goodsId'] as $key => $value) {
            $orderGoods = $this->entityManager->getRepository(OrderGoods::class)->findOneBy(['orderId' => $orderId, 'goodsId' => $value, 'goodsType' => 1]);
            if ($orderGoods) {
                $orderGoods->setDeliveryName($deliveryName[$data['deliveryId'][$key]]);
                $orderGoods->setGoodsStatus($status);
                $orderGoods->setExpressNumber($data['expressNumber'][$key]);
                $orderGoods->setExpressTime(time());
            }
        }
        $this->entityManager->flush();
        return true;
    }

    /**
     * 订单商品单独修改快递单号
     * @param $data
     * @param $orderId
     * @return bool
     */
    public function changeOrderGoodsExpressNumber($data, $orderId)
    {
        foreach ($data['goodsId'] as $key => $value) {
            $qb = $this->entityManager->createQueryBuilder();
            $qb->update(OrderGoods::class, 'g')
                ->set('g.expressNumber', ':expressNumber')->setParameter('expressNumber', $data['expressNumber'][$key])
                ->where('g.orderId = '.$orderId)
                ->andWhere('g.goodsId = '.$value);

            $qb->getQuery()->execute();
        }
        return true;
    }

    /**
     * 删除订单商品
     * @param $orderId
     * @return bool
     */
    public function deleteOrderGoods($orderId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(OrderGoods::class, 'g')->where('g.orderId = :orderId')->setParameter('orderId', $orderId);
        $qb->getQuery()->execute();

        return true;
    }

    /**
     * 复制订单商品封面图片
     * @param $goodsThumbnailImage
     * @param $goodsId
     * @return string|string[]|null
     */
    private function copyOrderGoodsImage($goodsThumbnailImage, $goodsId)
    {
        if(empty($goodsThumbnailImage) || substr($goodsThumbnailImage,0, 4) == 'http') return $goodsThumbnailImage;
        elseif(file_exists(Config::PUBLIC_PATH . $goodsThumbnailImage)) {
            $coverPath = Config::ORDER_GOODS_IMAGE_PATH.$goodsId;
            $coverImage= basename($goodsThumbnailImage);
            if(!is_dir($coverPath)) mkdir($coverPath, 0766, true);
            if(!file_exists($coverPath . '/' . $coverImage)) copy(Config::PUBLIC_PATH . $goodsThumbnailImage, $coverPath . '/' . $coverImage);
            return str_replace(Config::PUBLIC_PATH, '', $coverPath . '/' . $coverImage);
        }
        return null;
    }
}